<?php

namespace app\model;


use think\Model;
use think\facade\Cache;
use think\facade\Db;

class EcBrandModel extends Model
{
    

    /**
     * 该表将与模型关联。
     * @var string
     */
    protected $table = 'ec_brand';

    // 开启自动时间戳（默认为整型int）
    protected $autoWriteTimestamp = true;
    
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 返回 状态数据 访问器的值
     * @return string
     */
    public function getStatusDataAttr(): array
    {
        $data = [
            ['text' => '正常', 'value' => 1],
            ['text' => '禁用', 'value' => 0],
        ];
        return $data;
    }

    /**
     * 返回 状态 访问器的值
     * @return string
     */
    public function getStatusTextAttr()
    {
        $value = $this->getData('status');
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getStatusDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }

    /**
     * 使用视图查询
     */
    public function scopeDbView($query)
    {
        return $query->table('v_ec_brand');
    }

    /**
     * 返回一维数组的包含KV结构的数据
     */
    public static function getDictData($categoryId)
    {
        $categoryId = EcCategoryModel::getPid($categoryId);
        $cacheKey = "ec_brand_dict_data_{$categoryId}";
        $data = Cache::get($cacheKey);
        if ($data) {
            return $data;
        }
        $data = Db::table((new static())->table)->where('category_id', $categoryId)->field('id as value, brand_name as text')->select()->toArray();
        array_unshift($data, ['value' => 0, 'text' => '请选择品牌']);
        Cache::set($cacheKey, $data);
        ModelUtils::cachePut('ec_brand',$cacheKey);
        return $data;
    }
}
